import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {PageSubject} from '../../../../util/page-subject';
import {MsgResult} from '../../../../models/msg-result';
import {ActivatedRoute, Router} from '@angular/router';
import {ResponseUtil} from '../../../../util/response-util';
import {Path} from '../../../../portal/admin/admin-breadcrumb/breadcrumb';
import {OneDialogService} from '../../../../widgets/one-dialog/one-dialog.service';
import {MsgConstants} from '../../../../constants/constants';
import {SiteCategorysService} from '../site-categorys.service';
import {SiteCategorys} from '../site-categorys';
import {DataDictionaryService} from '../../../../services/dataDictionary.service';
import {TreeUtil} from '../../../../util/tree-util';

@Component({
  selector: 'app-site-categorys-add',
  templateUrl: './site-categorys-add.component.html',
  styleUrls: ['./site-categorys-add.component.css']
})
export class SiteCategorysAddComponent implements OnInit {
  // 声明实例
  siteCate: SiteCategorys;
  id: string;
  siteCateForm: FormGroup;

  // 数据字典中获取数据的编码
  dicPolluteType = 'ZDLEWRY';
  dicFuncCate = 'ZDLX';
  dicPolluteArr: Array<any> = [];
  dicFuncCateArr: Array<any> = [];

  // 所有站点类型数据
  allSiteCateArr: Array<any> = [];

  /**
   * 校验字段
   */
  formErrors = {
    'siteTypeName': '',
    'siteTypeCode': '',
    'functionalCategory': '',
    'monitorCategory': '',
    'remark': ''
  };

  /**
   * 校验提示信息
   */
  validationMessages = {
    'siteTypeName': {
      'required': '不能为空',
      'pattern': '请输入汉字，字母，或数字',
      'maxlength': '长度不能超过30',
    },
    'siteTypeCode': {
      'required': '不能为空',
      'maxlength': '长度不能超过3',
      'pattern': '只能是数字',
    },
    'monitorCategory': {
      'required': '不能为空'
    },
    'functionalCategory': {
      'required': '不能为空'
    },
    'remark': {
      'maxlength': '长度不能超过200'
    }
  };
  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private fb: FormBuilder,
    private responseUtil: ResponseUtil,
    private treeUtil: TreeUtil,
    private pageSubject: PageSubject,
    private dialogService: OneDialogService,
    private siteCateService: SiteCategorysService,
    private dicService: DataDictionaryService
  ) {
    this.initObject();
  }

  ngOnInit() {
    this.pushPage();
    this.getDicPolluteType();
    this.getAllSiteCate();
  }

  /**
   * 面包屑导航
   */
  pushPage() {
    const path = new Path('设备接入管理', '');
    this.pageSubject.pushPage('站点类型', '新增', path);
  }


  /**
   * 构造表单
   */
  buildForm(): void {
    this.siteCateForm = this.fb.group({
      'id': [this.siteCate.id],
      'siteTypeName': [this.siteCate.siteTypeName, [
        Validators.required,
        Validators.pattern(/^[\u4e00-\u9fa50-9A-Za-z]+$/),
        Validators.maxLength(30),
      ]],
      'siteTypeCode': [this.siteCate.siteTypeCode, [
        Validators.required,
        Validators.maxLength(3),
        Validators.pattern(/^[0-9]+$/),
      ]],
      'monitorCategory': [this.siteCate.monitorCategory, [
        Validators.required
      ]],
      'functionalCategory': [this.siteCate.functionalCategory, [
        Validators.required
      ]],
      'remark': [this.siteCate.remark],
      'isUse': [this.siteCate.isUse || '0', [
        Validators.required,
        Validators.maxLength(1)
      ]],
      'pId': [this.siteCate.pId]
    });

    this.siteCateForm.valueChanges.subscribe(
      data => this.onValueChanged(data)
    );
    this.onValueChanged();
  }
  /**
   * 值变化监听
   * @param data
   */
  onValueChanged(data?: any) {
    if (!this.siteCateForm) {
      return;
    }
    const form = this.siteCateForm;
    for (const field in this.formErrors) {
      if (this.formErrors.hasOwnProperty(field)) {
        this.formErrors[field] = '';
        const control = form.get(field);
        if (control && control.dirty && !control.valid) {
          const messages = this.validationMessages[field];
          for (const key in control.errors) {
            if (control.errors.hasOwnProperty(key)) {
              this.formErrors[field] += messages[key] + ' ';
            }
          }
        }
      }
    }
  }



  /**
   * 添加站点类型
   */
  onSubmit() {
    this.siteCate = this.siteCateForm.value;
    const pIdAr = this.siteCate.pId;
    this.siteCate.pId = pIdAr[pIdAr.length - 1];
    this.siteCateService.postSiteCate(this.siteCate).subscribe(
      result => this.responseUtil.success(result, this.processResult),
      message => this.responseUtil.error(message)
    );
  }

  /**
   *  获取添加信息
   * @param result
   */
  private processResult = (result: MsgResult) => {
    if (result && result.code === MsgConstants.MSG_CODE_OK) {
      this.dialogService.successWithCancelBtn('添加成功，是否继续添加？', () => this.initObject(), () => this.cancelSiteCateAdd());
    }
    if (result && result.code !== MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  };
  /**
   * 取消添加
   */
  cancelSiteCateAdd() {
    this.router.navigate(['..'], {relativeTo: this.route});
  }

  /**
   * 实例化对象
   */
  private initObject() {
    this.siteCate = new SiteCategorys();
    this.buildForm();
  }
  /**
   * 获取所有站点类型
   */
  getAllSiteCate () {
    this.siteCateService.getAllSiteCate().subscribe(
      result => this.responseUtil.success(result,  () => {
        if (result && result.code === MsgConstants.MSG_CODE_OK) {
          if (result.data.length > 0) {
            this.allSiteCateArr = this.treeUtil.wrapToStandard([].concat(result.data));
          }
        }
        if (result && result.code !== MsgConstants.MSG_CODE_OK) {
          this.dialogService.info(result.message);
        }
      }),
      error => this.responseUtil.error(error)
    );
  }
  /**
   * 获取数据字典中站点类型-大类
   */
  getDicPolluteType () {
    this.dicService.getChildDicByCode(this.dicPolluteType).subscribe(
      result => this.responseUtil.success(result,  () => {
        if (result && result.code === MsgConstants.MSG_CODE_OK) {
          if (result.data.length > 0) {
            this.dicPolluteArr = result.data;
            this.getDicFuncCate();
          }
        }
        if (result && result.code !== MsgConstants.MSG_CODE_OK) {
          this.dialogService.info(result.message);
        }
      }),
      error => this.responseUtil.error(error)
    );
  }
  getDicFuncCate = () => {
    this.dicService.getChildDicByCode(this.dicFuncCate).subscribe(
      result => this.responseUtil.success(result, () => {
        if (result && result.code === MsgConstants.MSG_CODE_OK) {
          if (result.data.length > 0) {
            this.dicFuncCateArr = result.data;
          }
        }
        if (result && result.code !== MsgConstants.MSG_CODE_OK) {
          this.dialogService.info(result.message);
        }
      }),
      error => this.responseUtil.error(error)
    );
  }
}
